package com.zz.yt.lib.annex.picture;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.GsonUtils;
import com.whf.android.jar.util.log.LatteLogger;
import com.zz.yt.lib.annex.BitmapUtils;
import com.zz.yt.lib.annex.R;
import com.zz.yt.lib.annex.document.bean.AnnexBean;
import com.zz.yt.lib.annex.loader.ImageLoaderArrayUtils;
import com.zz.yt.lib.annex.path.IRestClientPath;
import com.zz.yt.lib.annex.picture.adapter.PictureAdapter;
import com.zz.yt.lib.annex.listener.OnClickPictureCallback;
import com.zz.yt.lib.annex.listener.OnClickPictureListener;
import com.zz.yt.lib.annex.popup.utils.PicturePopupLocalUtils;
import com.zz.yt.lib.annex.constant.PictureConstant;

import java.util.List;


/**
 * 图片
 *
 * @author qf
 */
public class PictureView extends RelativeLayout implements OnClickPictureListener,
        OnClickPictureCallback {


    private final PictureAdapter mPictureAdapter;

    /**
     * 总共个数，默认9个
     */
    private int maxSelectNum;
    /**
     * 是否单张图片选择，默认是false
     */
    private boolean isRadio;
    /**
     * 是否能点击预览，默认是true
     */
    private boolean isPreview;

    /**
     * 添加图片方式
     */
    private int addition;
    private boolean isCompress;
    private int afterWidth, afterHeight;

    /**
     * 上下文
     */
    private Activity act;

    /**
     * 上下文
     */
    private Fragment mFragment;

    /**
     * 默认相册不能拍照
     */
    private boolean isCamera;

    /*** 是否图片裁剪，默认是false*/
    private boolean isCropping;

    /*** 默认不显示上传成功的图片*/
    private boolean isDisplay;

    /*** 图片选择回调*/
    private OnClickPictureCallback mClickPictureCallback = null;

    /*** 图片选择回调 */
    private View.OnClickListener mClickBackListener = null;

    /*** 上传回调 */
    private IRestClientPath mRestClientPath = null;


    public PictureView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // 加载布局
        LayoutInflater.from(context).inflate(R.layout.haian_view_picture, this, true);
        //Adapter
        mPictureAdapter = new PictureAdapter();
        mPictureAdapter.setOnItemClickListener(this);

        TextView mTextMust = findViewById(R.id.img_image);
        RecyclerView mRecyclerView = findViewById(R.id.recyclerview);
        final TextView text = findViewById(R.id.id_text);

        //TypedArray
        final TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.PictureView);
        if (attributes != null) {

            //总共个数，默认9个
            String title = attributes.getString(R.styleable.PictureView_title_test);
            if (text != null && !TextUtils.isEmpty(title)) {
                text.setText(title);
            }

            //总共个数，默认9个
            maxSelectNum = attributes.getInt(R.styleable.PictureView_max_display_count, 9);
            mPictureAdapter.setSelectMax(maxSelectNum);

            //是否显示删除，默认显示
            final boolean delete = attributes.getBoolean(R.styleable.PictureView_is_delete, true);
            mPictureAdapter.setDelete(delete);

            //每行显示个数，默认3个
            final int eachLineCount = attributes.getInt(R.styleable.PictureView_each_line_count, 3);
            GridLayoutManager manager = new GridLayoutManager(context, eachLineCount);
            mRecyclerView.setLayoutManager(manager);

            //是否显示添加，默认是true
            final boolean isAdded = attributes.getBoolean(R.styleable.PictureView_is_added, true);
            mPictureAdapter.setIncrease(isAdded);

            //是否能点击预览，默认是true
            isPreview = attributes.getBoolean(R.styleable.PictureView_is_preview, true);

            //是否是单张图片选择，默认是true
            isRadio = attributes.getBoolean(R.styleable.PictureView_is_radio, false);

            //是否相册显示拍照，默认是false
            isCamera = attributes.getBoolean(R.styleable.PictureView_is_camera, false);

            //是否显示上传成功的图片，默认是false
            isDisplay = attributes.getBoolean(R.styleable.PictureView_is_display, false);

            //是否是必传，默认是true
            final boolean isMust = attributes.getBoolean(R.styleable.PictureView_is_must, true);
            if (mTextMust != null) {
                mTextMust.setVisibility(isMust ? VISIBLE : GONE);
            }

            isCompress = attributes.getBoolean(R.styleable.PictureView_is_compress, false);
            afterWidth = attributes.getInteger(R.styleable.PictureView_after_width, 1080);
            afterHeight = attributes.getInteger(R.styleable.PictureView_after_height, 1920);

            //添加图片方式
            addition = attributes.getInt(R.styleable.PictureView_addition, PictureConstant.CAMERA);

            //设置Adapter
            mRecyclerView.setAdapter(mPictureAdapter);

            attributes.recycle();

        }
    }

    /**
     * @param shown:显示隐藏
     */
    public final void setShown(boolean shown) {
        setVisibility(shown ? VISIBLE : GONE);
    }

    /**
     * @param radio:是否单张图片选择
     */
    public PictureView setRadio(boolean radio) {
        isRadio = radio;
        if (isRadio) {
            maxSelectNum = 1;
        }
        return this;
    }

    /**
     * 上下文
     */
    public PictureView setContent(Context context) {
        this.act = (Activity) context;
        return this;
    }

    /**
     * 上下文
     */
    public PictureView setContent(Activity activity) {
        this.act = activity;
        return this;
    }

    /**
     * 上下文
     */
    public PictureView setContent(Fragment fragment) {
        this.mFragment = fragment;
        return this;
    }

    /**
     * @param isCamera Whether to open camera button
     */
    public PictureView isCamera(boolean isCamera) {
        this.isCamera = isCamera;
        return this;
    }

    /**
     * @param display:是否显示上传图片
     */
    public PictureView setDisplay(boolean display) {
        this.isDisplay = display;
        return this;
    }

    /**
     * @param cropping: 是否裁剪
     */
    public PictureView setCropping(boolean cropping) {
        isCropping = cropping;
        return this;
    }

    /**
     * @param isAdd:是否显示添加图标
     */
    public PictureView isAdd(boolean isAdd) {
        if (mPictureAdapter != null) {
            mPictureAdapter.setIncrease(isAdd);
        }
        return this;
    }

    /**
     * @param isDelete:是否显示删除图标
     */
    public PictureView isDelete(boolean isDelete) {
        if (mPictureAdapter != null) {
            mPictureAdapter.setDelete(isDelete);
        }
        return this;
    }

    /**
     * @param mRestClientPath:上传回调
     */
    public PictureView setRestClientPath(IRestClientPath mRestClientPath) {
        this.mRestClientPath = mRestClientPath;
        return this;
    }

    /**
     * @param callback：选择回调
     */
    public void setClickPictureCallback(OnClickPictureCallback callback) {
        this.mClickPictureCallback = callback;
    }

    @Override
    public void setOnClickListener(@Nullable OnClickListener l) {
        mClickBackListener = l;
    }

    @Override
    public void onPhotoClick() {
        switch (addition) {
            case PictureConstant.CAMERA:
                PicturePopupLocalUtils.create(this)
                        .setContent(act)
                        .setContent(mFragment)
                        .setMaxCount(maxSelectNum)
                        .setCropping(isCropping)
                        .setRadio(isRadio)
                        .requestCamera();
                break;
            case PictureConstant.GALLERY:
                PicturePopupLocalUtils.create(this)
                        .setContent(act)
                        .setContent(mFragment)
                        .setMaxCount(maxSelectNum)
                        .setCropping(isCropping)
                        .setRadio(isRadio)
                        .chooseRequest();
                break;
            case PictureConstant.ALL:
            default:
                PicturePopupLocalUtils.create(this)
                        .setContent(act)
                        .setContent(mFragment)
                        .setMaxCount(maxSelectNum)
                        .setCropping(isCropping)
                        .setRadio(isRadio)
                        .popup();
                break;
        }
        if (mClickBackListener != null) {
            mClickBackListener.onClick(this);
        }
    }

    @Override
    public void onItemClick(View view, int position) {
        if (isPreview) {
            if (mPictureAdapter != null) {
                List<Object> url = mPictureAdapter.getDataImage();
                ImageLoaderArrayUtils.create(null, url)
                        .setCurrentPosition(position)
                        .show();
            }
        }
    }

    /**
     * @param path：回调上传后的图片
     */
    public void addData(AnnexBean path) {
        if (isDisplay) {
            if (mPictureAdapter != null) {
                mPictureAdapter.addData(path);
            }
        }
    }

    /**
     * @param path：回调上传后的图片
     */
    public void addData(String path) {
        addData(new AnnexBean(path));
    }

    /**
     * @param result：回调上传后的图片
     */
    public void setDataObject(List<String> result) {
        if (mPictureAdapter != null) {
            mPictureAdapter.addAllData(result);
        }
    }

    @Override
    public void onCallback(List<String> selectList) {
        LatteLogger.i(GsonUtils.toJson(selectList));
        final List<String> resultCompress = BitmapUtils.compressIMG(getContext(),
                selectList, isCompress, afterWidth, afterHeight);
        if (mClickPictureCallback != null) {
            mClickPictureCallback.onCallback(resultCompress);
        }
        if (isDisplay) {
            //不直接添加在控件中、上传后通过addData添加。
            if (mRestClientPath != null) {
                mRestClientPath.setSelect(selectList, new IRestClientPath.OnClickAnnexCallback() {
                    @Override
                    public void filePath(List<AnnexBean> filePath) {
                        if (filePath != null) {
                            for (AnnexBean pathBean : filePath) {
                                addData(pathBean);
                            }
                        }
                    }
                });
            }
            return;
        }
        if (mPictureAdapter != null) {
            mPictureAdapter.addAllData(resultCompress);
        }
    }

    @Override
    public void remove(int position) {
        if (mClickPictureCallback != null) {
            mClickPictureCallback.remove(position);
        }
        if (mPictureAdapter != null) {
            mPictureAdapter.remove(position);
        }
    }

}
